/**
 * 2017年5月1日
 */
package cn.edu.bjtu.entity.impl.api;

import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;

import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import cn.edu.bjtu.constant.Constant;
import cn.edu.bjtu.settings.ApplicationConfiguration;
import pojo.dto.services.DocumentVectorMessage;
import util.io.LibSVMWriter;


/**
 * @author Alex
 *
 */
public class Word2VecFileTransContext extends Word2VecBaseContext<DocumentVectorMessage>{
	String wechatDir = ApplicationConfiguration.getInstance().getProperty("WECHAT_RAW_DATA_DIR");
	String uri =  "/post/transfile";
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	String filename;
	public Word2VecFileTransContext(ReadWriteLock lock) {
		super(lock);
		
	}

	@Override
	public String getMethod() {
		return METHOD_POST;
	}
	public HttpEntity getPostEntity() {
		File f = new File(this.wechatDir, filename);
		if(!f.exists()){
			return null;
		}
		HttpEntity he = MultipartEntityBuilder.create().addBinaryBody("file", f).build();
		return he;
	};
	
	@Override
	public Map<String, Object> getResultMapForRender() {
		return this.resultMap;
	}
	
	@Override
	public URI getURI() {
		return URI.create(uri);
	}
	private DocumentVectorMessage dvm;
	@Override
	protected void handleResponseInputStream(InputStream in, HttpEntity entity) throws Exception {
			dvm  = om.readValue(in, DocumentVectorMessage.class);		
			resultMap.put(Constant.COMMAND_RESULT, dvm);
			String s = sdf.format(new Date());
			if(dvm.getData() == null || dvm.getData().length == 0){
				this.resultMap.put("tip", "数据异常");
				throw new Exception("data 异常");
			}
			String dir = ApplicationConfiguration.getInstance().getProperty("WORD2VEC_TRANSFORMED_DIR");
			File target = new File(dir,s);
			if(!target.exists()){
				target.createNewFile();
			}
			new LibSVMWriter(target, dvm.getData()).write();
			this.msg = "转换成功";
			this.resultMap.put("tip", "成功写入文件");
	}
	
	public void setFilename(String filename) {
		this.filename = filename;
	}

	@Override
	public DocumentVectorMessage javaClassResult() {
		return dvm;
	}

	
}
